package com.diaohw.module.websocket.service.ws;

import com.diaohw.module.websocket.obj.dto.MsgDTO;
import com.diaohw.module.websocket.obj.enums.WSStatusEnums;
import com.diaohw.module.websocket.obj.vo.MsgVO;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.diaohw.platform.common.constant.RequestConstant.AUTHORIZATION;

@Slf4j
public class MessageHandle {
    protected static final Map<String, Map<String, List<Session>>> SubscribeMap = new ConcurrentHashMap<>();


    public static MsgVO sendMessage(MsgDTO data) {

        List<Session> sessions = getSessions(data.getTopic(), data.getSubscribeId(), data.getToken());

        sessions.forEach(session -> session.getAsyncRemote().sendObject(data.getData()));

        WSStatusEnums type = sessions.isEmpty() ? WSStatusEnums.FAILED : WSStatusEnums.SUCCESS;
        String str = null;
        if (sessions.isEmpty()) {
            str = "目标不在线";
        }

        MsgVO msgVO = MsgVO.of(str, type, data.getTopic(), data.getSubscribeId(), !sessions.isEmpty(), data.getToken());
        msgVO.setId(data.getMsgId());
        return msgVO;
    }


    public static String getToken(Session session) {
        return (String) session.getUserProperties().get(AUTHORIZATION);
    }


    private static List<Session> getSessions(String topic, String subscribeId, String token) {
        if (!SubscribeMap.containsKey(topic) || !SubscribeMap.get(topic).containsKey(subscribeId)) {
            return List.of();
        }

        return SubscribeMap.get(topic).get(subscribeId).stream()
                .filter(session -> token == null || token.equals(getToken(session)))
                .toList();
    }


}
